package com.ItemsRent.Interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.ItemsRent.action.LoginAction;
import com.ItemsRent.model.Customer;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.util.ValueStack;

/**
 * 登录拦截
 * @author yrf
 *
 */
public class LoginInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public String intercept(ActionInvocation arg) throws Exception {
		Object obj = arg.getAction();
		System.out.println(obj.getClass());
		System.out.println(LoginAction.class);
		HttpSession session = ServletActionContext.getRequest().getSession();
	    HttpServletRequest request = ServletActionContext.getRequest();
		Customer user = (Customer) session.getAttribute("customer");
		String cuNumber = (String) session.getAttribute("cuNumber");
		if(user!=null&&cuNumber!=null&&user.getNumber().equals(cuNumber)){
			System.out.println("这是拦截器， 用户 "+user.getNumber()+" 登陆成功");
			return arg.invoke();
		}else if(obj.getClass().equals(LoginAction.class)){
			return arg.invoke();
		}
		else{
			System.out.println("这是拦截器， 用户  登陆失败");
			if(isAjaxRequest(request)){
				ValueStack stack = arg.getStack();
				 Map<String, Object> returnResult = new HashMap<String, Object>();
				// 向根对象加入1个MAP, KEY值与(<paramname="root">returnResult</param></result>)
				        //中root的值相同
				 stack.set("returnResult", returnResult);	
				 returnResult.put("code", "001");
				 returnResult.put("NoRight", "true");
				 returnResult.put("msg", "你尚未登录，请先登录！");
				 return "inputjson";
			}else
			return "input";
		}
	}
	
	private boolean isAjaxRequest(HttpServletRequest request){
		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equals(header))
			return true;
		else
			return false;
	}

}
